import {getSetting,chooseAddress,openSetting,showModal,showToast,requestPayment} from "../../utils/asyncWx"
// 语法转换的包
import regeneratorRuntime from '../../lib/runtime/runtime';
import { request } from "../../request/index";
Page({

  /**
   * 页面的初始数据
   */
  data: {
    address:{},
    cart:[],
    allChecked :false,
    totalPrice:0,
    totalNum:0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {

  },
  onShow(){
    // 获取缓存中的地址
    const address = wx.getStorageSync("address");
    // 获取缓存中的购物车的数据
    let cart = wx.getStorageSync("cart")||[];
    cart = cart.filter(v => v.checked)
    this.setData({address})
      // 总价格 总数量
      let totalPrice = 0;
      let totalNum = 0;
      cart.forEach(v => {
        if (v.checked) {
          totalPrice += v.num * v.goods_price;
          totalNum += v.num;
        } 
      });
      this.setData({
        cart,
        totalPrice,
        totalNum,
        address
      })
  },
  async handleOrderPay(){
   try {
    const token = wx.getStorageSync("token");
    if (!token) {
      wx.navigateTo({
        url: '/pages/auth/index',
      
      });
      return
    }
    // 创建订单 请求头参数
    // const header={Authorization:token}
    // 请求体参数
    const order_price=this.data.totalPrice
    const consignee_addr=this.data.address.all
    const cart = this.data.cart
    let goods=[]
    cart.forEach(v=>goods.push({
      goods_id:v.goods_id,
      goods_number:v.num,
      goods_price:v.goods_price
    }))
    const orderParame = {order_price,consignee_addr,goods}
    //发送请求获取订单编号
    const {order_number} = await  request({url:"/my/order",method:"post",data:orderParame})
    //预支付请求
    const {pay} = await request({url:"/my/orders/req_unifiedorder",method:"post",data:{order_number}})
    //调用微信支付
    await requestPayment(pay);
    //查询后台的状态 获取订单详情
    const res = await request({url:"/my/orders/chkOrder",method:"post",data:{order_number}}) 
    await showToast({title:"支付成功"})
    //手动删除缓存中的数据
    let newCart = wx.getStorageSync("cart");
      newCart = newCart.filter(v=> !v.checked);
    wx.setStorageSync("cart", newCart);
      
    //支付成功后跳转到订单页面
    wx.navigateTo({
      url: '/pages/order/index',
    }); 
   } catch (error) {
    await showToast({title:"支付失败"})
    console.log(error);
   }
  }
 
})